package org.iryshka.skyserver;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HTMLBuilder {
	static private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy   HH:mm");

	private static String URLEscapeReplace(String resourceStr) {
		return resourceStr.replace("%", "%25").replace("<", "%3C").replace(">", "%3E").replace("#", "%23")
			.replace(" ", "%20").replace("{", "%7B").replace("}", "%7D").replace("|", "%7C").replace("\\", "%5C")
			.replace("^", "%5E").replace("~", "%7E").replace("[", "%5B").replace("]", "%5D").replace("`", "%60")
			.replace(";", "%3B").replace("/", "%2F").replace("?", "%3F").replace(":", "%3A").replace("@", "%40")
			.replace("=", "%3D").replace("&", "%26").replace("$", "%24");
	}
	
	private static String getTime(File file) {
		return dateFormat.format(file.lastModified());
	}
	
	private static String formHref(final String folderName, final String fileName) {
		return folderName + "/" + URLEscapeReplace(fileName);
	}
	
	public static String formHtmlList(final File requestedDir, final String serverDir) throws IOException {
		final StringBuilder formedListResponse = new StringBuilder(500);
		formedListResponse
				.append(("<html><head><title>HOSTNAME /"
						+ requestedDir.getName()
						+ "</title>"
						+ "<h2> hostname /" + requestedDir.getName() + "/</h2>"
						+ "<hr><pre >" + "<a href=\"/\">[To Parent Directory]</a><br>"));
		final File[] filesInDir = requestedDir.listFiles();
		String relativeServerPath = requestedDir.getAbsolutePath().replaceAll("\\\\", "/");
		relativeServerPath = relativeServerPath.substring(serverDir.length(), relativeServerPath.length());
		for (final File F : filesInDir) {
			formedListResponse.append("<br>" + getTime(F) + "  "
					+ FileHelper.getSpaceRecursive(F.getAbsoluteFile()) + "  ");
			formedListResponse.append("<a href=\""
					+ formHref(relativeServerPath, F.getName()) + "\">"
					+ F.getName() + "</a>");
		}
		formedListResponse.append("<br></pre><hr></body></html>");
		return formedListResponse.toString();
	}
	
	private static String decorateError(String error, String message) {
		return String.format("<html><head><title>%1$st</title></head><body>%2$s</body></html>",	error, message);
	}

	public static String getErrorHtml (String code) {
		return decorateError(HTTPResponse.getMessageFromStatus(code), HTTPResponse.getExtMessageFromStatus(code));
	}
}
